﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;
using System.Text;


public class PushMsgManger : MonoBehaviour
{
    #if UNITY_IOS 
    public void InitRegisterForNotifications()
    {
        UnityEngine.iOS.NotificationServices.RegisterForNotifications(UnityEngine.iOS.NotificationType.Alert | UnityEngine.iOS.NotificationType.Sound);
        string registrationError = UnityEngine.iOS.NotificationServices.registrationError;
        if (!string.IsNullOrEmpty(registrationError))
        {
            Debug.LogError("Notification regist error " + registrationError);
        }
        else
        {
            StopCoroutine("Wait");
            StartCoroutine("Wait");
        }
    }

    private IEnumerator Wait()
    {
        for(int i =0; i < 10; ++i)
        {
            if(UnityEngine.iOS.NotificationServices.deviceToken != null)
            {
                SendToken();
                yield break;
            }
            else
            {
                yield return new WaitForSeconds(1);
            }
        }
        SendToken();
    }

    private void SendToken()
    {
        byte[] deviceToken = UnityEngine.iOS.NotificationServices.deviceToken;
        string tokenStr = string.Empty;
        if (deviceToken != null)
        {
            StringBuilder strBuilder = new StringBuilder();
            foreach (byte token in deviceToken)
            {
                strBuilder.Append(token.ToString("X2"));
            }
            tokenStr = strBuilder.ToString();
        }
        Debug.Log("notification token: "+tokenStr);
        ProtoBuf.Message.CSDeviceTokenInfo msg = new ProtoBuf.Message.CSDeviceTokenInfo();
        msg.deviceToken = tokenStr;
		msg.deviceId = GameConfig.Instance.GetDeviceID;
        msg.appVersion = GameConfig.Instance.AppVersion;
        msg.resVersion = GameConfig.Instance.resPackageVersion;
        msg.channelId = GameConfig.Instance.GetChannelId;
        NetAPI.SendHttpInBackground(ProtoBuf.Message.OpDefine.CSDeviceTokenInfo, msg, null);
    }

    private void Awake()
    {
        instance = this;
    }
    public static PushMsgManger Instance
    {
        get
        {
            return instance;
        }
    }
    private static PushMsgManger instance;
    #endif
}